//
//  OMGoodSearchViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2017/4/20.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMGoodSearchViewController.h"
#import "OMSearchBar.h"
#import "OMSearchHistoryItemCollectLayout.h"
#import "OMSearchHistoryItemCollectCell.h"
#import "OMCollectionSearchHistoryItemCollectHeader.h"
#import "OMCollectionSearchHotItemCollectHeader.h"

#import "OMGoodTwoColumnCollectDelegater.h"
#import "OMGoodTwoColumnFlowLayout.h"

#define kGoodSearchHistoryMaxNum 16
#define kGoodSearchHistoryKey @"good_search_historys"

#import "BaseTableView.h"
#import "OMGoodSearchEditingTableDelegater.h"

@interface OMGoodSearchViewController () <OMSearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,OMCollectionSearchItemCollectHeaderDelegate>
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) UICollectionView *resultCollectView;
@property (nonatomic, strong) OMGoodTwoColumnCollectDelegater *resultDelegater;
@property (nonatomic, strong) UITableView *editingTableView;
@property (nonatomic, strong) OMGoodSearchEditingTableDelegater *editDelegater;
@property (nonatomic, strong) NSMutableArray <OMProduct*>*goods;
@property (nonatomic, strong) NSArray *searchStrs;

@property (nonatomic, strong) NSArray *historyItems;
@property (nonatomic, strong) NSArray *hotItems;

@property (nonatomic, assign) NSUInteger pageSize;
@property (nonatomic, assign) NSUInteger pageNumber;

@end

@implementation OMGoodSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    _goods = [NSMutableArray array];
    _historyItems = SMUserDefaultGet(kGoodSearchHistoryKey);
    [self getHotItems];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    SMNotificationPost(_resultCollectView.hidden?SM_NOTIFACATION_NEED_CARTITEM_DISMISS:SM_NOTIFACATION_NEED_CARTITEM_SHOW, nil);
}


#pragma mark - UI setup
static NSString *headerHistoryIdentifier = @"OMCollectionSearchHistoryItemCollectHeader";
static NSString *headerHotIdentifier = @"OMCollectionSearchHotItemCollectHeader";
- (void)setupUI
{
    self.view.backgroundColor = SM_whiteColor;
    [self searchBarSetup];
    [self collectViewSetup];
    [self resultCollectViewSetup];
    [self editingTableViewSetup];

}

OMSearchBar *searchBar = nil;
- (void)searchBarSetup
{
    //搜索框
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.title = nil;
    searchBar = [OMSearchBar new];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, SM_SCREEN_WIDTH, SM_SIZE(60));
    self.navigationItem.titleView = searchBar;
    [searchBar startEdit];
}

- (void)collectViewSetup
{
    //搜索记录与热门搜索
    _collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[OMSearchHistoryItemCollectLayout new]];
    [_collectView registerClass:[OMSearchHistoryItemCollectCell class] forCellWithReuseIdentifier:[OMSearchHistoryItemCollectCell cellIdentifier]];
    [_collectView setContentInset:UIEdgeInsetsMake(SM_SIZE(40), 0, 0, 0)];
    [_collectView registerClass:[OMCollectionSearchHistoryItemCollectHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerHistoryIdentifier];
    [_collectView registerClass:[OMCollectionSearchHotItemCollectHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerHotIdentifier];
    _collectView.delegate = self;
    _collectView.dataSource = self;
    _collectView.alwaysBounceVertical = true;
    _collectView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectView];
    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.left.equalTo(@0);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];
}

- (void)resultCollectViewSetup
{

    //搜索结果显示
    _resultCollectView = [[UICollectionView alloc]initWithFrame:CGRectZero
                                           collectionViewLayout:[OMGoodTwoColumnFlowLayout new]];
    _resultDelegater = [[OMGoodTwoColumnCollectDelegater alloc]initWithCollectionView:_resultCollectView];
    _resultCollectView.backgroundColor = SM_backGroundColor;
    [self.view addSubview:_resultCollectView];
    [_resultCollectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.bottom.right.left.equalTo(@0);
    }];
    _resultCollectView.hidden = true;

    //分页
    @weakify(self);
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        self.pageNumber++;
        [self searchWithText:searchBar.text];
    }];
    footer.stateLabel.font = SM_CFont(24);
    footer.stateLabel.textColor = SM_darkGrayColor;
    footer.triggerAutomaticallyRefreshPercent = SM_SIZE(-20);
    footer.automaticallyHidden = true;
    [footer setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
    self.resultCollectView.mj_footer = footer;
}

- (void)editingTableViewSetup
{
    //搜索框编辑中搜索字段选择显示
    _editingTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _editingTableView.backgroundColor  = SM_backGroundColor;
    _editingTableView.tableFooterView = [UIView new];
    _editingTableView.separatorColor = SM_naviShadowColor;
    _editDelegater = [[OMGoodSearchEditingTableDelegater alloc]initWithTableView:_editingTableView];
    @weakify(self);
    [_editDelegater setSelctionHandler:^(NSUInteger index) {
        //点击搜索
        @strongify(self);
        ((OMSearchBar *)self.navigationItem.titleView).text = self.searchStrs[index];
    }];
    [self.view addSubview:_editingTableView];
    [_editingTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.bottom.right.left.equalTo(@0);
    }];
    _editingTableView.hidden = true;
}


#pragma mark - Actions
//处理搜索后，搜索记录的存储操作
- (void)configureHistoryWithEditedSearchBar:(OMSearchBar *)searchBar
{
    NSMutableArray *tempArray = _historyItems?[_historyItems mutableCopy]:[@[] mutableCopy];
    NSUInteger index = 0;
    BOOL isExist = NO;
    for (NSString *item in tempArray) {
        if ([searchBar.text isEqualToString:item]) {
            [tempArray removeObject:item];
            isExist = YES;
            break;
        }
        index++;
    }
    if (!isExist||(index != 0 && isExist)) {
        [tempArray insertObject:searchBar.text atIndex:0];
        if (tempArray.count > kGoodSearchHistoryMaxNum) {
            [tempArray removeObjectsInRange:NSMakeRange(kGoodSearchHistoryMaxNum-1, tempArray.count-kGoodSearchHistoryMaxNum)];
        }
        SMUserDefaultSet(kGoodSearchHistoryKey, tempArray);
        _historyItems = tempArray;
        [self.collectView reloadData];
    }
}


/**
 重载
 */
- (void)reload
{
    self.resultDelegater.goods = self.goods;
}



/**
 设置检索数组

 @param searchStrs <#searchStrs description#>
 */
- (void)setSearchStrs:(NSArray *)searchStrs
{
    _searchStrs = searchStrs;
    self.editDelegater.searchStrs = searchStrs;
}



/**
 搜索

 @param text <#text description#>
 */
- (void)searchWithText:(NSString *)text
{
    [self showSearchResultView];
    self.resultDelegater.loading = true;
    [self.task cancel];
    self.task =
    [KTHttpUtils POST:@"search.jhtml"
           parameters:@{@"keyword":text,@"pageSize":@(self.pageSize),@"pageNumber":@(self.pageNumber)}
            needToken:false
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        self.resultDelegater.loading = false;

        if (isSuccess) {

            NSArray <OMProduct *>*goods = [OMProduct mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
            for (OMProduct *good in goods) {
                good.image = [responseObject[OMImagePrefix] stringByAppendingString:good.image?:@""];
            }
            if (!self.resultCollectView.mj_footer.isRefreshing) {
                [self.goods removeAllObjects];
            }
            [self.goods addObjectsFromArray:goods];
            goods.count<self.pageSize?[self.resultCollectView.mj_footer endRefreshingWithNoMoreData]:[self.resultCollectView.mj_footer endRefreshing];
            [self reload];

        }else {
            if (self.resultCollectView.mj_footer.isRefreshing) {
                [self.resultCollectView.mj_footer endRefreshing];
                self.pageNumber --;
            }
            [OMHUD HUDInfo:@"加载失败"];
        }
    }];
}


/**
 检索

 @param text <#text description#>
 */
- (void)getSearchStrsWith:(NSString *)text
{
    [self showEditView];
    [self.task cancel];
    self.task =
    [KTHttpUtils POST:@"search.jhtml"
          parameters:@{@"keyword":text,@"pageNumber":@(1),@"pageSize":@(30)}
           needToken:false
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
              if (isSuccess) {
                  NSArray <OMProduct *>*goods = [OMProduct mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
                  NSMutableArray *searchStrs = [NSMutableArray arrayWithCapacity:goods.count];
                  for (OMProduct *good in goods) {
                      [searchStrs addObject:good.name];
                  }
                  self.searchStrs = searchStrs;
              }
          }];

}

- (void)getHotItems
{
    [KTHttpUtils GET:@"search/hotSearch.jhtml"
          parameters:nil
           needCache:true
           needToken:false
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
              if (isSuccess) {
                  _hotItems = responseObject[OMDatumKey]?:@[];
              }else {
                  _hotItems = @[@"珠江啤酒",@"雪花",@"梁丰",@"教士",@"怡宝",@"怡泉",@"阿尔卑斯",@"啤酒",@"维他奶",@"天地壹号",@"乐事大波浪薯片(蕃茄味)",@"泰奇八宝粥",@"养元",@"无穷",@"百岁山"];
              }
              [self.collectView reloadData];
    }];
}

- (void)showEditView
{
    self.editingTableView.hidden = false;
    [self hideSearchResultView];
}

- (void)hideEditView
{
    self.editingTableView.hidden = true;
}

- (void)showSearchResultView
{
    self.resultCollectView.hidden = NO;
    [self hideEditView];
    SMNotificationPost(SM_NOTIFACATION_NEED_CARTITEM_SHOW, nil);
}

- (void)hideSearchResultView
{
    self.resultCollectView.hidden = YES;
    self.resultDelegater.goods = nil;
    SMNotificationPost(SM_NOTIFACATION_NEED_CARTITEM_DISMISS, nil);
}

#pragma mark - OMSearchBarDelegate
- (void)searchBarShouldReturn:(OMSearchBar *)searchBar
{
    [self configureHistoryWithEditedSearchBar:searchBar];
    self.pageNumber = 1;
    [self searchWithText:searchBar.text];
}

- (void)searchBar:(OMSearchBar *)searchBar shouldChangeText:(NSString *)text
{
    NSLog(@"searchText=%@\ntext=%@",searchBar.text,text);
    if ((searchBar.text.length == 1 && text.length == 0) || (!searchBar.text.length && !text.length)) {
        [self hideSearchResultView];
        [self hideEditView];
    }else{
        [self getSearchStrsWith:[searchBar.text?:@"" stringByAppendingString:text?:@""]];
    }
}

- (void)searchBarShouldClear:(OMSearchBar *)searchBar
{
    [self hideSearchResultView];
    [self hideEditView];
}

- (void)searchbarDidClickCancelButton:(OMSearchBar *)searchBar
{
    NaviPopAnimated(true);
}

- (BOOL)searchBarShouldBeginEditing:(OMSearchBar *)searchBar
{
    if (searchBar.text.length) {
        [self getSearchStrsWith:searchBar.text];
    }
    return YES;
}

#pragma mark - OMCollectionSearchItemCollectHeaderDelegate
- (void)didSelectRightButtonOnHeader:(OMCollectionSearchItemCollectHeader *)header atSection:(NSUInteger)section
{
    if ([header isKindOfClass:[OMCollectionSearchHistoryItemCollectHeader class]]) {
        //删除搜索历史
        SMUserDefaultSet(kGoodSearchHistoryKey, @[]);
        _historyItems = @[];
        [self.collectView reloadData];
    }
}

#pragma mark - UICollectionViewLayoutDelegate && UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (_historyItems.count && _hotItems.count) {
        return 2;
    }else if (_historyItems.count || _hotItems.count) {
        return 1;
    }
    return 0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_historyItems.count && section == 0) {
        return _historyItems.count;
    }
    return _hotItems.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    OMSearchHistoryItemCollectCell *cell = [OMSearchHistoryItemCollectCell collectCellWithCollectionView:collectionView atIndexPath:indexPath];
    if (_historyItems.count && indexPath.section == 0) {
        [cell configureCellWithObj:_historyItems[indexPath.item]];
        cell.isHot = NO;
    }else {
        [cell configureCellWithObj:_hotItems[indexPath.item]];
        cell.isHot = indexPath.item < 4;
    }

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        NSString *identifer = (_historyItems.count && indexPath.section == 0) ? headerHistoryIdentifier : headerHotIdentifier;
        OMCollectionSearchItemCollectHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:identifer forIndexPath:indexPath];
        header.delegate = self;
        return header;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_historyItems.count && indexPath.section == 0) {
        return [OMSearchHistoryItemCollectCell itemSizeWithContent:_historyItems[indexPath.item]];
    }
    return [OMSearchHistoryItemCollectCell itemSizeWithContent:_hotItems[indexPath.item]];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *searchText = nil;
    if (_historyItems.count && indexPath.section == 0) {
       searchText = _historyItems[indexPath.item];
    }else {
       searchText = _hotItems[indexPath.item];
    }
    ((OMSearchBar *)self.navigationItem.titleView).text = searchText;
}



///MARK:分页

/**
 分页大小

 @return <#return value description#>
 */
- (NSUInteger)pageSize
{
    if (_pageSize < 20) {
        _pageSize = 20;
    }
    return _pageSize;
}


/**
 分页页码

 @return <#return value description#>
 */
- (NSUInteger)pageNumber
{
    if (!_pageNumber) {
        _pageNumber = 1;
    }
    return _pageNumber;
}
@end
